#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>

#include "err_handle.h"
#define BUF_SIZE 1024
int main(int argc, char *argv[])
{
    int sock_cln = 0;
    int rv = 0;
    struct sockaddr_in serv_addr = {0};
    char buf[256] = {0};
    ssize_t read_len = 0;
    ssize_t write_len = 0;
    ssize_t read_len_temp = 0;

    if (argc != 3)
    {
        printf("usage :%s <ip><port>. \n", argv[0]);
        return -1;
    }
    sock_cln = socket(PF_INET, SOCK_STREAM, 0);
    if (sock_cln == -1)
    {
        error_handling("socket() error. \n");
    }

    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(atoi(argv[2]));
    // inet_pton(AF_INET,"127.0.0.1", &serv_addr.sin_addr.s_addr);
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]); //htonl(INADDR_ANY)
    rv = connect(sock_cln, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    if (rv == -1)
    {
        error_handling("connect() error .\n");
    }

    while (1)
    {
        fputs("1.名字2.时间3.名字和时间4.阴历(Q to quit):   \n ", stdout);
        fgets(buf, BUF_SIZE, stdin);

        if (!strcmp(buf, "q\n") || !strcmp(buf, "Q\n"))
        {
            break;
        }

        if (strcmp(buf, "4\n") == 0)
        {
            fputs("输入日期：\n", stdout);
            fgets(buf, BUF_SIZE, stdin);
        }
        write_len = write(sock_cln, buf, strlen(buf));
        read_len = 0;
        while (read_len < write_len)
        {
            read_len_temp = read(sock_cln, &(buf[read_len]), BUF_SIZE - read_len - 1);
            if (read_len == -1)
            {
                error_handling("read() error");
            }
            read_len += read_len_temp;
        }
        buf[read_len] = 0;
        printf("message from server: %s \n", buf);
    }

    close(sock_cln);
    return 0;
}

//打印客户端ip端口信息
/*char ip[32];
    printf("客户端的IP:%s, 端口:%d\n",
            inet_ntop(AF_INET, &caddr.sin_addr.s_addr,ip,sizeof(ip)),
                ntohs(caddr.sin_port));*/
